
package com.optimize.elasticsearch.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.optimize.elasticsearch.config.EsClientConfig;
import com.optimize.elasticsearch.entry.OriginalHour;
import com.optimize.elasticsearch.service.OriginalHourService;
import jdk.nashorn.internal.parser.JSONParser;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.*;

/**
 * <p>
 * 地面小时数据表 前端控制器
 * </p>
 *
 * @author zx
 * @since 2024-09-25
 */
@RestController
@RequestMapping("/originalHour")
public class OriginalHourController {

    @Resource
    private OriginalHourService originalHourService;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            10,
            60,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<>(),
            new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setName("my-thread-" + thread.getId());
                    return thread;
                }
            },
            new ThreadPoolExecutor.DiscardOldestPolicy()
    );

    @RequestMapping("/getOriginalHour")
    public String getOriginalHour() {
        List<OriginalHour> originalHourList = originalHourService.list(new LambdaQueryWrapper<OriginalHour>()
                .eq(OriginalHour::getYear, 2024)
                .eq(OriginalHour::getMonth, 9)
                .eq(OriginalHour::getDay, 25));

        executor.submit(() -> {
            originalHourList.forEach(originalHour -> {
                String json = originalHour.getDay().toString();
                insertData("original_hour", String.valueOf(originalHour.getId()), json);
            });
        });

        return "成功";
    }


    /**
     * 向 Elasticsearch 插入数据
     *
     * @param index 索引名称
     * @param id    文档 ID（如果为 null，则自动生成）
     * @param json  JSON 格式的数据
     * @return 插入结果
     */
    public String insertData(String index, String id, String json) {
        IndexRequest request = new IndexRequest(index);
        if (id != null) {
            request.id(id); // 设置文档 ID
        }
        request.source(json, XContentType.JSON); // 设置文档内容

        try {
            IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            return response.toString(); // 返回插入结果
        } catch (IOException e) {
            throw new RuntimeException("Error while inserting data into Elasticsearch", e);
        }
    }


}
